package com.cse.index;

import java.io.*;

import jeasy.analysis.MMAnalyzer;

import org.apache.log4j.Logger;
import org.apache.lucene.analysis.*;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.cse.config.PropertyConfiguration;
import com.cse.core.Product;
import com.cse.service.BaseService;



public class ProductIndexer {
	private static Logger logger = Logger.getLogger(ProductIndexer.class);
	
	private static ProductIndexer indexer;

	private String indexPath = "";
	
	private IndexWriter writer = null;
	
	private Analyzer analyzer = null;
	
	private BaseService service;
	
	private String index_path = PropertyConfiguration.getIndexStorePath();

	private ProductIndexer()  {
		this.indexPath = index_path;
		ApplicationContext ctx	= new  ClassPathXmlApplicationContext("/spring-conf.xml");
		service = (BaseService) ctx.getBean("baseService");
		try {
			initialize();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static synchronized ProductIndexer getIndexer(){
		if(indexer == null){
			indexer = new ProductIndexer();
			return indexer;
		}
		else{ 
			return indexer;
		}
	}

	/**
	 * 
	 * @throws Exception
	 */
	private void initialize() throws Exception {
		  analyzer = new MMAnalyzer();
		  File root = new File(indexPath);          
          if (root == null || root.listFiles() == null || root.listFiles().length == 0) {  
        	  logger.info("当前的索引为创建型索引");
              writer = new IndexWriter(indexPath, analyzer,true);  
          } else {  
              logger.info("当前的索引为追加型索引");
              
              writer = new IndexWriter(indexPath, analyzer, false);  
          }  
		
	}
	
	public void close() {
		try{
			writer.close();
		} catch(Exception e) {
			e.printStackTrace();
			writer = null;
		}
	}
	
	public void addProduct(Product product) throws Exception {
	    service.addProduct(product);
		Document doc = ProductDocument.buildProductDocument(product);
		writer.addDocument(doc);
		

	}
	
	public void optimizeIndex() throws Exception {
		writer.optimize();
	}
	

}
